const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors=require('cors')
const fs=require('fs');
var uuid = require('node-uuid');
const indexRouter = require('./routes/index');
const typesRouter = require('./routes/articleType/index');
const articlesRouter = require('./routes/article/index');
const usersRouter = require('./routes/user/index');
const loginRouter = require('./routes/login/index');
const app = express();
const expressSwagger = require('express-swagger-generator')(app);
const accessLogStream = fs.createWriteStream(__dirname + '/utils/logs/access.log', {flags: 'a'});
const errorLogStream = fs.createWriteStream(__dirname + '/utils/logs/error.log', {flags: 'a'});
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
let options = {
    swaggerDefinition: {
        info: {
            description: '大事件Api接口',
            title: '大事件管理系统',
            version: '1.0.0',
        },
        host: 'localhost:3000',
        basePath: '/',
        produces: [
            "application/json",
            "application/xml"
        ],
        schemes: ['http', 'https'],
        securityDefinitions: {
            JWT: {
                type: 'apiKey',
                in: 'header',
                name: 'authorization',
                description: "",
            }
        }
    },
    basedir: __dirname,
    files: ['./routes/**/*.js']
};
expressSwagger(options);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
logger.token('id', function getId (req) {
  return req.id
})
app.use(cors());
app.use(assignId);
// app.use(logger(':id :method :url :status :date[iso] :response-time' ,{stream:accessLogStream}));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/', typesRouter);
app.use('/', articlesRouter);
app.use('/', usersRouter);
app.use('/', loginRouter);

const skipSuccess = (req, res)  => res.statusCode < 400;
const skipError = (req, res) => res.statusCode >= 400;
app.use(logger('combined', {
  skip: skipError,
  stream: accessLogStream
}))

app.use(logger('combined', {
  skip: skipSuccess,
  stream: errorLogStream
}))
app.use(function (req, res, next) {
  next(createError(404));
});
app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});
function assignId (req, res, next) {
  req.id = uuid.v4()
  next()
}
module.exports = app;
